package com.lollipop.common.listeners;

import com.lollipop.common.annotation.Start;
import com.lollipop.common.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;


@Slf4j
@Component
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext parentApplicationContext = event.getApplicationContext().getParent();
        log.debug("{}spring容器已经完成.{}", StringUtils.center("", 20, ">"), StringUtils.center("", 20, "<"));
        if (parentApplicationContext == null) { //顶层applicationContext;
            ApplicationContext applicationContext = event.getApplicationContext();
            Map<String, Object> needInitBeans = applicationContext.getBeansWithAnnotation(Start.class);
            for (Object service : needInitBeans.values()) {
                log.debug(">>>>> {}.init()", service.getClass().getName());
                try {
                    Method initMapper = service.getClass().getMethod("init");
                    initMapper.invoke(service);
                } catch (Exception e) {
                    log.error("初始化@Start注解的bean的init方法异常", e);
                    e.printStackTrace();
                }
            }
            Map<String, BaseService> needInitService = applicationContext.getBeansOfType(BaseService.class);
            for (BaseService service : needInitService.values()) {
                log.debug(">>>>> {}.init()", service.getClass().getName());
                try {
                    Method init = service.getClass().getMethod("init");
                    init.invoke(service);
                } catch (Exception e) {
                    log.error("初始化BaseService的init方法异常", e);
                    e.printStackTrace();
                }
            }
        }
    }
}
